package cn.tsa.share.jdbc.shardingjdbc;

import cn.hutool.core.collection.CollUtil;
import cn.tsa.share.jdbc.shardingjdbc.hint.OrderHintParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 强制路由分片策略
 *
 * @author hongwei
 */
@Slf4j
public class OrderHintShardingAlgorithm implements HintShardingAlgorithm<OrderHintParam> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<OrderHintParam> hintShardingValue) {
        List<OrderHintParam> orderHintParams = hintShardingValue.getValues().stream().collect(Collectors.toList());
        String logicTableName = hintShardingValue.getLogicTableName();
        List<String> tablesName = new ArrayList<>();
        OrderHintParam orderHintParam = orderHintParams.get(0);
        int[] index = orderHintParam.getIndex();
        for (Integer value : index) {
            String tableName = logicTableName + value;
            if (!availableTargetNames.contains(tableName)) {
                log.error("invalid values in shardingResults:{}", value);
                throw new IllegalArgumentException("invalid value in hintShardingValue!");
            }
            tablesName.add(tableName);
        }
        if (CollUtil.isNotEmpty(tablesName)) {
            tablesName.add(logicTableName);
        }
        return tablesName;
    }
}
